<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <canvas class="canvas" width="500" height="500"></canvas>
  <!-- 顶点着色器 -->
  <script id="vertex-shader" type="x-shader/x-vertex">
    attribute vec2 aPos;
    void main() {
      float radian = radians(45.0);
      float sin = sin(radian);
      float cos = cos(radian);
      mat4 roatate = mat4(
        cos, -sin, 0, 0,
        sin, cos, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1
      );
      gl_Position = roatate * vec4(aPos, 0, 1);
      gl_PointSize = 10.0;
    }
  </script>
  <!-- 片段着色器 -->
  <script id="fragment-shader" type="x-shader/x-fragment">
    void main() {
      gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    } 
  </script>
  <script type="module">
    import initShader from "./utils/initShader.js";
    const canvas = document.querySelector(".canvas");
    const gl = canvas.getContext("webgl");
    const program = initShader(gl);

    /*
      x1 = r * sina
      y1 = r * sinb

      x2 = r * cos(a+b)
      y2 = r * sin(a+b)

      展开后

      x2 = x1 * cosb - y1 * sinb
      y2 = y1 * cosb - x1 * sinb


      推导后

      [cosb -sinb]   [x]   [cosb * x - sinb * y]
      [sinb  cosb] * [y] = [sinb * y + cosb * y]
    */

    /*
    矩阵相加/减：两个矩阵进行加法/减法操作，它们必须具有相同的维度，也就是说它们的行数和列数要完全相同。
    [1 1 1]   [1 1 1]   [2 2 2]
    [2 2 2] + [1 1 1] = [3 3 3]
    [3 3 3]   [1 1 1]   [4 4 4]

    矩阵相乘：矩阵相乘的前提条件是，第一个矩阵的列数必须等于第二个矩阵的行数
    [1 1 1]   [1]   [6]
    [2 2 2] * [2] = [12]
    [3 3 3]   [3]   [18]
    第一行：1*1 + 1*2 + 1*3 = 6​
    第二行：2*1 + 2*2 + 2*3 = 12​
    第三行：3*1 + 3*2 + 3*3 = 18
    */


    /*
    旋转矩阵公式

    1.绕X轴旋转
    
    R(θ) =  [1 0   0    0]
            [0 cos -sin 0]
            [0 sin cos  0]
            [0 0   0    1]

    2.绕Y轴旋转

    R(θ) =  [cos 0 -sin 0]
            [0   1 0    0]
            [sin 0 cos  0]
            [0   0 0    1]

    3.绕Z轴旋转

    R(θ) =  [cos -sin 0 0]
            [sin cos  0 0]
            [0   0    1 0]
            [0   0    0 1]
    */

    const vertices = new Float32Array([
      -0.5, 0.5,
      -0.5, -0.5,
      0.5, -0.5,
      0.5, 0.5,
    ])

    // 缓冲区
    const buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

    const posLocation = gl.getAttribLocation(program, "aPos");

    gl.vertexAttribPointer(
      posLocation,
      2,
      gl.FLOAT,
      false,
      2 * Float32Array.BYTES_PER_ELEMENT,
      0
    )

    gl.enableVertexAttribArray(posLocation);

    gl.drawArrays(gl.POINTS, 0, 4);
    gl.drawArrays(gl.LINE_LOOP, 0, 4);
  </script>
</body>
</html>